package civicinity.ist.psu.edu.share;

import java.util.ArrayList;
import java.util.Comparator;

import org.json.JSONArray;
import org.json.JSONObject;

import civicinity.ist.psu.edu.CivicinityLogin;
import civicinity.ist.psu.edu.CivicinityMainpage;
import civicinity.ist.psu.edu.R;
import civicinity.ist.psu.edu.adapter.CivicinityLazyAdapter;
import civicinity.ist.psu.edu.adapter.CivicinityShareListViewAdapter;
import civicinity.ist.psu.edu.constants.Constants;
import civicinity.ist.psu.edu.databases.CivicinityDatabase;
import civicinity.ist.psu.edu.rssfeed.CivicinityFeedLists;
import civicinity.ist.psu.edu.rssfeed.RSSReader;
import civicinity.ist.psu.edu.utils.CivicinityCameraMode;
import civicinity.ist.psu.edu.utils.DownloadHandler;
import edu.emory.mathcs.backport.java.util.Collections;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.location.Location;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class CivicinityShareListview extends Activity implements OnItemClickListener{

	private ArrayList<ShareItem> mArrItem = new ArrayList<ShareItem>();
	private ArrayList<ShareItem> mShareOthersArr = new ArrayList<ShareItem>();
	private ImageView changeViewBtn;
	private ImageView cameraBtn;
	
	private static final int SELECT_PICTURE = 1;
	private String mSelectedImagePath;
	
	private CivicinityDatabase mDB;
	
	private ProgressBar mSpinner;
	private TextView mLoadingTxt;
	
	private boolean mReadyToOnResume = false;
	private SharedPreferences mPref;
	
	private int mType = 0;
	
	private static final int SORT_LOCATION = 1;
	private static final int SORT_TIME = 2;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.share_list_view);
	
	    changeViewBtn = (ImageView) findViewById(R.id.view_change);
	    cameraBtn = (ImageView) findViewById(R.id.camera_mode);
	    mSpinner = (ProgressBar) findViewById(R.id.spinner);
	    mLoadingTxt = (TextView) findViewById(R.id.loading_text);
	    
	    mDB = new CivicinityDatabase(this);
	    mPref = PreferenceManager.getDefaultSharedPreferences(this);
	    //setListView();
	    
	    new downloadShareList().execute();
	    
	    changeViewBtn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//startActivity(new Intent(CivicinityShareListview.this, CivicinityMainpage.class));
				startActivity(new Intent(CivicinityShareListview.this, CivicinityShareMapview.class));
				finish();
			}
		});
	    
	    cameraBtn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				if(mPref.getBoolean("guest_mode", false)) {
					new AlertDialog.Builder(CivicinityShareListview.this)
			   		.setTitle("Upload photo")
			   		.setMessage("Make sure you are able to take a photo and save it into the SD card, but cannot upload a photo to the server since you logged in as 'GUEST'")
			   		.setPositiveButton("Okay", new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							openDialog();
						}
					})
			   		.show();
				}
				else {
					openDialog();
				}
			}
		});
	    // TODO Auto-generated method stub
	}
	
	public void openDialog() {
		final CharSequence[] choiceSeq = {"Choose from Gallery", "Capture a photo"};
		
		new AlertDialog.Builder(CivicinityShareListview.this)
   		.setTitle("Upload photo")
   		.setItems(choiceSeq, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				if(which == 0) {
					Intent intent = new Intent();
                    intent.setType("image/*");
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                    startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE);
				}
				else {
					Intent intent = new Intent(CivicinityShareListview.this, CivicinityCameraMode.class);
					intent.putExtra("prev_activity", Constants.PREV_ACITIVITY_SHARE);
					startActivity(intent);
				}
			}
		})
   		.show();
	}
	
	@Override
	public void onResume() {
		super.onResume();
		Log.i("K", "start onResume()");
		
		if(mReadyToOnResume) {
			setOtherShareView();
		}
	}
	
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
	    if (resultCode == RESULT_OK) {
	        if (requestCode == SELECT_PICTURE) {
	            Uri selectedImageUri = data.getData();
	            mSelectedImagePath = getPath(selectedImageUri);
	            
	            Intent intent = new Intent(this, CivicinityMyView.class);
	            intent.putExtra("image_path", mSelectedImagePath);
	            startActivity(intent);
	            
	            finish();
	        }
	    }
	}

	public String getPath(Uri uri) {
	    String[] projection = { MediaStore.Images.Media.DATA };
	    Cursor cursor = managedQuery(uri, projection, null, null, null);
	    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
	    cursor.moveToFirst();
	    return cursor.getString(column_index);
	}
	
	private void setOtherShareView() {
		
		// sort method is not applied in this condition.
		if(mType == 0 || mType == 1) {
			mShareOthersArr = mDB.getShareOthers(mType);
			if(mShareOthersArr.size() == 0) {
				Toast.makeText(this, "No Here&Now by you.", Toast.LENGTH_SHORT).show();
				return;
			}
		}
		
		ListView vList = (ListView) findViewById(R.id.itemlist);
		CivicinityShareListViewAdapter adapter = new CivicinityShareListViewAdapter(this, R.layout.share_item, mShareOthersArr);
		vList.setAdapter(adapter);
		vList.setOnItemClickListener(this);
		vList.setSelection(0);
		
		vList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
		    @Override
		    public boolean onItemLongClick(AdapterView<?> av, View v, int pos, long id) {
		        return onLongListItemClick(v,pos,id);
		    }
		});
	}
	
	private void setMyListView() {

		mArrItem = mDB.getShareMe();
		if(mArrItem.size() == 0) {
			Toast.makeText(this, "No events so far", Toast.LENGTH_SHORT).show();
		}
		else {
			// set the RSS items
			ListView vList = (ListView) findViewById(R.id.itemlist);
			CivicinityShareListViewAdapter adapter = new CivicinityShareListViewAdapter(this, R.layout.share_item, mArrItem);
			vList.setAdapter(adapter);
			vList.setOnItemClickListener(this);
			vList.setSelection(0);
			
			vList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
			    @Override
			    public boolean onItemLongClick(AdapterView<?> av, View v, int pos, long id) {
			        return onLongListItemClick(v,pos,id);
			    }
			});
		}
	}
	
	/**
	 * Download share components from the server
	 * @author kyunghan
	 *
	 */
	class downloadShareList extends AsyncTask<Void, Void, Void> {

		@Override
		protected Void doInBackground(Void... arg0) {
			// TODO Auto-generated method stub
			
			DownloadHandler dHandler = new DownloadHandler();
			String getResponse = dHandler.downloadJson(Constants.DOWNLOAD_SHARE_INFO + "?start_idx=0");

			Log.i("K", "getResponse : " + getResponse);
			
			try{
				JSONObject jObj = new JSONObject(getResponse);
				
				if(jObj.getBoolean("success")) {
					JSONArray jsonAry = new JSONArray(jObj.getString("results"));
					
					double latitude = Double.parseDouble(mPref.getString("latitude", "0.0"));
					double longitude = Double.parseDouble(mPref.getString("longitude", "0.0"));
					
					for(int i = 0; i < jsonAry.length(); i++){
						
						float dist[] = new float[1];
						Location.distanceBetween(latitude, longitude, 
								Double.parseDouble(jsonAry.getJSONObject(i).getString("latitude")), 
								Double.parseDouble(jsonAry.getJSONObject(i).getString("longitude")), dist);
						
						ShareItem item = new ShareItem();
						item.setEventID(Integer.parseInt(jsonAry.getJSONObject(i).getString("id")));
						item.setEventUsername(jsonAry.getJSONObject(i).getString("username"));
						item.setEventDate(jsonAry.getJSONObject(i).getString("datetime"));
						item.setEventDescription(jsonAry.getJSONObject(i).getString("description"));
						item.setEventCategory(jsonAry.getJSONObject(i).getString("category"));
						item.setEventLatitude(Double.parseDouble(jsonAry.getJSONObject(i).getString("latitude")));
						item.setEventLongitude(Double.parseDouble(jsonAry.getJSONObject(i).getString("longitude")));
						item.setEventAccuracy(Float.parseFloat(jsonAry.getJSONObject(i).getString("accuracy")));
						item.setEventPhotoUrl(jsonAry.getJSONObject(i).getString("image"));
						item.setEventCommentCnt(jsonAry.getJSONObject(i).getInt("comment_cnt"));
						item.setEventLike(jsonAry.getJSONObject(i).getInt("like"));
						item.setEventCheckInCnt(jsonAry.getJSONObject(i).getInt("checkin"));
						item.setEventDistance(dist[0]);
						
						Log.i("K", "dist[0] : " + dist[0]);
						
						
						mShareOthersArr.add(item);
					
					}
					Log.d("K", "download shared info : success to store into db");
				}
				
				mDB.setShareOthers(mShareOthersArr);
				
				mType = 0;
				
			} catch(Exception e){}
			
			
			return null;
		}
		
		@Override
	  	protected void onPostExecute(Void unused) {
			
			mSpinner.setVisibility(View.GONE);
			mLoadingTxt.setVisibility(View.GONE);
			
			mReadyToOnResume = true;
			
			onResume();
		}
		
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
		// TODO Auto-generated method stub
		Intent intent = new Intent(CivicinityShareListview.this, CivicinityShareInfo.class);
		intent.putExtra("event_id", mShareOthersArr.get(position).getEventID());
		
		startActivity(intent);
	}
	
    /**
     * LongListPress event
     * @param v
     * @param position
     * @param id
     * @return
     */
    protected boolean onLongListItemClick(View v, final int position, long id) {
        return true;
    }
    
    
    /**
	 * Menu option(non-Javadoc)
	 * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
	 */
	public boolean onCreateOptionsMenu(Menu menu){
		super.onCreateOptionsMenu(menu);
		
		menu.add(0, 1, 0, getString(R.string.all_here_and_now)).setIcon(android.R.drawable.ic_menu_slideshow);
		menu.add(0, 2, 0, getString(R.string.my_here_and_now)).setIcon(android.R.drawable.ic_menu_myplaces);
		menu.add(0, 3, 0, getString(R.string.sort_here_and_now)).setIcon(android.R.drawable.ic_menu_sort_by_size);
			
		return true;
	}
	
	/**
	 * Menu option selection handling(non-Javadoc)
	 * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
	 */
	public boolean onOptionsItemSelected(MenuItem item){
		switch(item.getItemId()){
			case 1:
				//startActivity(new Intent(CivicinityShareListview.this, MyHereAndNow.class));
				mType = 0;
				mReadyToOnResume = true;
				
				onResume();
				return true;
			case 2:
				mType = 1;
				mReadyToOnResume = true;
				
				onResume();
				return true;
			case 3:
				final CharSequence[] choiceSeq = {"By Location", "By Time"};
				
				// show dialog to choose the type.
				new AlertDialog.Builder(CivicinityShareListview.this)
		   		.setTitle("Sort type")
		   		.setItems(choiceSeq, new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						if(which == 0) {
							// by location.
							sortArrayItems(SORT_LOCATION);
						}
						else {
							// by time.
							sortArrayItems(SORT_TIME);
						}
					}
				})
		   		.show();
				
				return true;
		}
		return false;
	}
	
	/**
	 * sort the array by type
	 * @param type: 1-location, 2-time(which is default)
	 */
	private void sortArrayItems(int type) {
		// start sorting
		//mShareOthersArr
		
		if(type == SORT_LOCATION) {
			
			for(int i = 0 ; i < mShareOthersArr.size() ; i++) {
				Log.i("K", "Dist: " + mShareOthersArr.get(i).getEventDistance());
			}
			
			mType = 2;
			Comparator<ShareItem> compare = new Comparator<ShareItem>() {

				@Override
				public int compare(ShareItem obj1, ShareItem obj2) {
					// TODO Auto-generated method stub
					return String.valueOf(obj2.getEventDistance()).compareToIgnoreCase(String.valueOf(obj1.getEventDistance()));
				}
			};
			
			Collections.sort(mShareOthersArr, compare);
			
			for(int i = 0 ; i < mShareOthersArr.size() ; i++) {
				Log.i("K", "Dist: " + mShareOthersArr.get(i).getEventDistance());
			}
			
		}
		else if(type == SORT_TIME) {
			mType = 0;
		}
		
		// start onResume.
		mReadyToOnResume = true;
		onResume();
	}
}
